package br.com.br1.fv.mobile;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import br.com.br1.fv.mobile.activity.MainActivity;

import android.content.Context;
import android.content.Intent;


public class FlowControl implements Serializable{

	private static final long serialVersionUID = 1L;
	private static final Class<?> defaultActivity = MainActivity.class;
	
	private Collection<FlowLevel> levels;
	
	public FlowControl(){
		levels = new ArrayList<FlowControl.FlowLevel>();
	}

	public void addLevel(Class<?>...activities){
		FlowLevel l = new FlowLevel();
		for(Class<?> c:activities){
			l.activities.add(c);
		}
		levels.add(l);
	}
	
	public void registry(Intent i){
		i.putExtra(FlowControl.class.getName(), this);
	}
	
	public static FlowControl getFlowControl(Intent i){
		return (FlowControl) i.getSerializableExtra(FlowControl.class.getName());
	}

	public static Intent getNextActivity(Intent i, Class<?> currentActivity, Context ctx){
		FlowControl fc = getFlowControl(i);
		Class<?> nextActivityClass = defaultActivity;
		if(fc != null){
			for(Iterator<FlowLevel> ite = fc.levels.iterator(); ite.hasNext();){
				FlowLevel l = ite.next();
				if(l.containsActicvity(currentActivity) && ite.hasNext()){
					nextActivityClass = ite.next().activities.iterator().next();
					break;
				}
			}
		}
		
		Intent nextActivity = new Intent().setClass(ctx, nextActivityClass);
		if(fc != null){
			fc.registry(nextActivity);
		}
		return nextActivity;
	}
	
	private class FlowLevel implements Serializable{
		private static final long serialVersionUID = 1L;
		private Collection<Class<?>> activities = new ArrayList<Class<?>>();
		private boolean containsActicvity(Class<?> activity){
			return activities.contains(activity);
		}
	}
}
